//
//  EmojiPackage.swift
//  1-自定义键盘搭建
//
//  Created by yellow on 15/10/23.
//  Copyright © 2015年 yellow. All rights reserved.
//

import UIKit

/// 常量，一个表情cellGroup中有21个表情(包含一个删除按钮)
let collectionCellCount = 21

/// 表情种类
class EmojiPackage: NSObject {

    /// 表情组的资源所在的包名
    var id:String?
    
    /// 表情组名称
    var group_name_cn:String?
    
    /// 表情数组 - 能够保证，在使用的时候，数组已经存在，可以直接追加数据
    lazy var emoticons:[Emoji] = [Emoji]()
    
    
    
    init(dict:[String:AnyObject]) {
        super.init()
        id = dict["id"] as? String
        group_name_cn = dict["group_name_cn"] as? String
        
        //当有数组时
        if let emojiArray = dict["emoticons"] as? [[String:AnyObject]] {
            
            //记录每个表情的索引
            var index = 0
            for var emojiDict in emojiArray{
                if let png = emojiDict["png"],let dir = id{
                    //拼接 png 路径为 com.sina.lxh/lxh_pili.png -> png
                    emojiDict["png"] = dir + "/" + (png as! String)
                }
                emoticons.append(Emoji(dict: emojiDict))
                
                //因为每3*7个为一页，所以在20个的后面添加一个删除按钮
                if ++index == 20{
                    emoticons.append(Emoji(isDeleteBtn: true))
                    index = 0
                }
            }
            
        }
        bulidSpaceBtn()
    }
    
    
/// 构建空白按钮
    private func bulidSpaceBtn(){
        //当一组的个数%21有余数(或是0个表情,如:最近)，就需要在后面添加x(x=21-余数-1个按钮)个空白按钮
        if emoticons.count % collectionCellCount == 0 && emoticons.count != 0 {
            print("\(group_name_cn),满了")
        }else{
            //多2个，再补21-2空白按钮
            print(emoticons.count % collectionCellCount)
            let spaceBtnCount = collectionCellCount - emoticons.count%collectionCellCount
            
            for i in 1..<spaceBtnCount{
                emoticons.append(Emoji(isSpaceBtn: true))
            }
            
            //末尾补充一个删除按钮
            emoticons.append(Emoji(isDeleteBtn: true))
        }
    }
    
    override var description:String{
    
        let keys = ["id","group_name_cn","emoticons"]
        return dictionaryWithValuesForKeys(keys).description
    }
}
